package interface_layer;

import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database_layer.Common;
import database_layer.UpdateDispatcher;

/**
 * This servlet handles the user fields update in the web service
 */
public class UpdateUser extends HttpServlet
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateUser()
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
	{
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String username = (String) request.getSession().getAttribute("username");
				
			if (null == username)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
					
			HashMap<String, String> updatedDetails = new HashMap<String, String>();
			
			// Checking all the boxes
			if (null != request.getParameter("change_password"))
			{
				updatedDetails.put(Common.passwordField, request.getParameter("change_password_value"));
			}
			if (null != request.getParameter("change_first_name"))
			{
				updatedDetails.put(Common.firstNameField, request.getParameter("change_first_name_value"));
			}
			if (null != request.getParameter("change_last_name"))
			{
				updatedDetails.put(Common.lastNameField, request.getParameter("change_last_name_value"));
			}
			if (null != request.getParameter("change_phone_number"))
			{
				updatedDetails.put(Common.phoneField, request.getParameter("change_phone_number_value"));
			}
			if (null != request.getParameter("change_address"))
			{
				updatedDetails.put(Common.addressField, request.getParameter("change_address_value"));
			}
			
			int returnValue = UpdateDispatcher.updateUserDetails(username, updatedDetails);
			ErrorHandler.parseForErrors(returnValue, response, "userPage.jsp");
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}
}
